<template>
    <div>
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <!--左侧区域-->
                <span style="float: left">用户信息</span>
                <!--搜索框-->
                <el-col :span="5">
                    <el-input
                            clearable
                            size="medium"
                            v-model="keyWord"
                            placeholder="输入关键字搜索"/>
                </el-col>

                <!--右侧区域-->
                <el-col :span="2">
                    <el-button size="medium" type="success" plain @click="search">搜索</el-button>
                </el-col>
                <el-button style="margin-left: auto" :loading="viewAllFlag" icon="el-icon-refresh" type="primary" plain @click="viewAll">全部用户</el-button>
            </div>

            <div style="font-size: 14px;margin-bottom: 18px;">
                <el-table
                        :data="tableData.list"
                        style="width: 100%">
                    <el-table-column type="expand">
                        <!--表格详细信息-->
                        <template slot-scope="props">
                            <el-form label-position="left" inline class="demo-table-expand">
                                <el-form-item label="用户 ID">
                                    <span>{{ props.row.id }}</span>
                                </el-form-item>
                                <el-form-item label="用户账号">
                                    <!--角色提示信息-->
                                    <el-popover trigger="hover" placement="top">
                                        <span v-if="props.row.username==='admin'">这是管理员，拥有所有权限</span>
                                        <span v-else>这是普通用户，拥有一般权限</span>
                                        <div slot="reference" class="name-wrapper">
                                            <el-tag>
                                                <span>{{ props.row.username }}</span>
                                            </el-tag>
                                        </div>
                                    </el-popover>
                                </el-form-item>
                                <el-form-item label="邮箱">
                                    <span>{{ props.row.email }}</span>
                                </el-form-item>
                                <el-form-item label="密码">
                                    <span>{{ props.row.password }}</span>
                                </el-form-item>
                                <el-form-item label="加密盐">
                                    <span>{{ props.row.salt }}</span>
                                </el-form-item>
                                <el-form-item label="头像路径">
                                    <span>{{ props.row.avatar }}</span>
                                </el-form-item>
                                <el-divider><span style="color: #C0C4CC">用户权限</span></el-divider>
                                <el-form-item label="角色">
                                    <el-tag>
                                        <span>{{ props.row.rolesInfo }}</span>
                                    </el-tag>
                                    <el-button size="small" :loading="props.row.loading" type="info" plain icon="el-icon-refresh" @click="refreshRole(props.$index,props.row.username)">刷新缓存</el-button>
                                </el-form-item>
                                <!-- <el-form-item label="权限">
                                     <span>{{ props.row.permission }}</span>
                                 </el-form-item>-->
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column
                            width="120"
                            label="序号"
                            type="index"
                            :index='(index)=>{return (this.tableData.currentPage - 1) * this.tableData.pageSize + (index+1)}' >
                    </el-table-column>
                    <el-table-column
                            label="用户账号"
                            prop="username">
                    </el-table-column>
                    <el-table-column
                            label="邮箱"
                            prop="email">
                    </el-table-column>
                    <el-table-column
                            width="120"
                            align="center"
                            label="状态(锁定/正常)">
                        <template slot-scope="scope">
                            <el-popconfirm
                                    confirm-button-text='好的'
                                    cancel-button-text='不用了'
                                    icon="el-icon-info"
                                    icon-color="red"
                                    title="是否更改用户状态？" @confirm="confirmSwitch(scope.$index,scope.row.id)">
                                <el-switch
                                        slot="reference"
                                        disabled
                                        v-model="scope.row.status"
                                        :active-value="1"
                                        :inactive-value="0">
                                </el-switch>
                            </el-popconfirm>
                        </template>
                    </el-table-column>

                    <el-table-column
                            label="操作">
                        <template slot-scope="scope">
                            <el-button size="small" type="primary" @click="update(scope.$index,scope.row.id)">修改</el-button>
                            <!--具名插槽-->
                            <el-button size="small" type="danger" slot="reference" @click="delUser(scope.$index,scope.row.id,scope.row.username)">删除</el-button>
                        </template>

                    </el-table-column>
                </el-table>

                <!--分页-->
                <el-pagination class="nav-fenye"
                               @current-change="handleCurrentChange"
                               :current-page="this.tableData.currentPage"
                               :page-size="this.tableData.pageSize"
                               layout="total, prev, pager, next, jumper"
                               :total="this.tableData.total">
                </el-pagination>
            </div>
        </el-card>

        <!--修改信息弹窗-->
        <template>
            <el-dialog title="修改用户信息"
                       :before-close="handleClose"
                       :visible.sync="ab"
                       width="50%"
                       id="update">
                <el-form :model="form" label-position="right">
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="用户id" label-width="120px">
                                <p class="el-form-item__info">不可修改</p>
                                <el-input v-model="form.id" prefix-icon="el-icon-s-tools" autocomplete="off" :readonly="true"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="用户名称" label-width="120px">
                                <p class="el-form-item__info">不可修改</p>
                                <el-input v-model="form.username" prefix-icon="el-icon-s-custom" autocomplete="off" :readonly="true"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="10">
                        <el-form-item label="邮箱" label-width="120px">
                          <el-input v-model.trim="form.email" prefix-icon="el-icon-message" autocomplete="off"/>
                        </el-form-item>
                      </el-col>
                      <el-col :span="10">
                        <el-form-item label="密码" label-width="120px">
                            <p class="el-form-item__info">自动重置</p>
                            <el-input v-model.trim="form.password" prefix-icon="el-icon-lock" autocomplete="off" :readonly="true"/>
                        </el-form-item>
                      </el-col>
                      <!--提示信息-->
                      <el-popover
                          placement="top-start"
                          width="170"
                          trigger="hover"
                          content="重置密码，将用户的密码重置为 123456 ">
                        <el-button slot="reference" size="small" plain type="primary" class="resetPopover" @click="resetPassword">重置密码</el-button>
                      </el-popover>
                    </el-row>
                  <el-row>
                      <el-col :span="10">
                        <el-form-item label="加密盐" label-width="120px">
                            <p class="el-form-item__info">自动重置</p>
                            <el-input v-model.trim="form.salt" prefix-icon="el-icon-s-grid" autocomplete="off" :readonly="true"/>
                        </el-form-item>
                      </el-col>
                      <el-col :span="10">
                        <el-form-item label="头像路径" label-width="120px">
                            <p class="el-form-item__info">不可修改</p>
                            <el-input v-model="form.avatar" prefix-icon="el-icon-picture-outline-round" autocomplete="off" :readonly="true"/>
                        </el-form-item>
                      </el-col>

                    </el-row>
                    <el-row>
                      <el-col :span="10">
                        <el-form-item label="角色" label-width="120px">
                          <el-select v-model="selectRole" multiple placeholder="请选择">
                            <el-option-group
                                v-for="group in options"
                                :key="group.label"
                                :label="group.label">
                              <el-option
                                  v-for="item in group.options"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value">
                              </el-option>
                            </el-option-group>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <!--<el-col :span="10">
                            <el-form-item label="权限" label-width="120px">
                                <el-input v-model="form.permission" autocomplete="off"/>
                            </el-form-item>
                        </el-col>-->

                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="ab = false">取 消</el-button>
                    <el-button type="primary" @click="confirmUpdate()">确 定</el-button>
                </div>
            </el-dialog>
        </template>
    </div>
</template>

<style scoped>
    *{
        outline:none
    }
    .el-card__header{
        background-color: rgba(0,0,0,.03);
    }
    .el-card__body{
        padding-top: 0;
    }
    .clearfix{
        display: flex;
        align-items: center;
    }
    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }
    .box-card {
/*
        width: 480px;
*/
    }
    /*修改下拉框默认宽度*/
    .el-select{
      width: 260px;
    }

    tr{
        height: 60px;
    }
    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
    .el-form--inline .el-form-item__content{
        vertical-align: baseline;
    }
    .el-switch__label{
        color: #909399;
    }

    /*重写switch的disabled时css*/
    .el-switch.is-disabled{
        opacity: 1;
    }
    .el-switch.is-disabled .el-switch__core, .el-switch.is-disabled .el-switch__label{
        cursor: pointer;
    }
    .el-tag{
      cursor: pointer;
    }
    /*自定义弹出框样式*/
    .resetPopover {
      margin: 3px 10px;
    }
    /*input图标颜色*/
/*    .el-input__inner:hover .el-input__icon{
        color: #409EFF;
    }*/
    /*input提示*/
    .el-form-item__info {
        color: #C0C4CC;
        font-size: 10px;
        line-height: 1;
        padding-top: 4px;
        position: absolute;
        top: 85%;
        left: 8px;
    }
    /*修改信息弹窗间隔*/
    #update .el-col{
        margin-bottom: 5px;
    }

</style>

<script>
    module.exports = {
        //props : ['aaa'],
        components: {
            //'my-dialog': httpVueLoader('/static/vue/dialog.vue'),
        },
        data() {
            return {
              viewAllFlag : false,
              /*修改角色数据*/
              options: [{
                label: '管理员',
                options: [{
                  value: 'admin',
                  label: '超级管理员',
                  desc: '1',
                }, {
                  value: 'junior',
                  label: '普通管理员',
                  desc: '2',
                }]
              }, {
                label: '普通用户',
                options: [{
                  value: 'user',
                  label: '普通用户',
                  desc: '3',
                }, {
                  value: 'guest',
                  label: '来宾',
                  desc: '4',
                }]
              }],
              selectRole: [],//下拉框角色数组
              tableData : {//表格数据
                currentPage : 0,
                pageSize : 0,
                total : 0,
                list : 0,
              },
              keyWord : '',//搜索关键字
              form: {//表单数据
/*                id: '',
                username: '',
                password: '',
                email: '',
                salt: '',
                avatar: '',
                role: '',
                permission: ''*/
              },
              popoverVisible:false,//提示信息变量
              ab: false,//控制修改弹窗变量
              updateIndex: false,//全局表格下标变量
              formFlag: false,//判断表单数据是否修改过，默认未修改
            }
        },
        methods : {
          initData(page){//初始化数据
            axios({
              method : "GET",
              url:"/user/json/" + page,
            }).then((response)=>{
              console.log(response.data);
              this.tableData = response.data;
              for(let i = 0; i < this.tableData.list.length; i++) {
                //使用set添加响应式数据，直接添加，修改时无法相应视图
                this.$set(this.tableData.list[i], 'loading', false)
              }
            }).catch((error) => {
              console.log(error);
            });
          },
          handleCurrentChange(currentPage){//处理分页数据
            this.initData(currentPage)
          },
          viewAll(){//查看全部用户
            this.viewAllFlag = true;
            this.initData(1)
            setTimeout( ()=> {
              this.viewAllFlag = false;
            },1000)
          },
          search(){//关键字搜索
            if (this.keyWord === ""){
              this.$message.warning({showClose: true, message:'搜索关键字不能为空', offset:80});
            }
            axios({
              method : "GET",
              url:"/user/search/" + this.keyWord,
            }).then((response)=>{
              if (response.data !== ""){
                console.log(response.data);
                this.tableData = response.data
              }else{
                Qmsg.warning("没有找到你要搜索的数据，请尝试更改搜索条件",{autoClose:false, position:'center'});
              }
            }).catch((error) => {
              console.log(error);
            });
          },
          refreshRole(index, username){//刷新用户权限缓存
            this.tableData.list[index].loading = true
            axios({
              method : "GET",
              url:"/user/clearAuthorizationCache/" + username,
            }).then((response)=>{
              console.log(response.data);
              if (response.data === true){
                const h = this.$createElement;
                this.$notify.success({showClose: true,
                  message: h('p', null, [h('i', { style: 'color: teal' }, this.form.username), h('span', null, '刷新缓存成功 '),]), offset:80});
              }
            }).catch((error) => {
              console.log(error);
            })
            setTimeout( ()=> {
              this.tableData.list[index].loading = false
            },2000)
          },
          confirmSwitch(index ,id){//用户状态切换确认
            this.tableData.list[index].status = Number(!this.tableData.list[index].status)
            axios({
              method : "GET",
              url:"/user/updateStatus/" + id + "/" + this.tableData.list[index].status,
            }).then((response) => {
              if (response.data === true){
                this.$notify({type: 'success', title: '成功', message: '修改成功',});
              }
            }).catch((error) => {
              this.$notify({type: 'error', title: '错误', message: '修改失败',});
            });

          },
          update(index, id){//更新用户信息
            this.updateIndex = index
            axios({
              method : "GET",
              url:"/user/find/" + id,
            }).then((response)=>{
              console.log(response.data);
              this.form = response.data;
              this.selectRole = this.form.rolesInfo.split(",")//构建下拉框角色标签
              this.ab = true
            }).catch((error) => {
              console.log(error);
            });
          },
          resetPassword(){//重置密码 123456
            this.form.password = 'aeba418f412528ef49eb7b163c784e37'
            this.form.salt = 'eHFApsVl'
          },
          handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {//确认关闭时触发
                  this.form.email = null
                  done();
                })
                .catch(_ => {});
          },
          confirmUpdate(){//用户更新确认
            console.log(this.form)
            console.log(this.selectRole)
            axios({
              method : "POST",
              url :"/user/update",
              data : {
                id : this.form.id,
                email : this.form.email,
              },
            }).then((response)=>{
              if (response.data === true){
                const h = this.$createElement;
                this.$notify.success({showClose: true,
                  message: h('p', null, [h('i', { style: 'color: teal' }, this.form.username), h('span', null, '修改成功 '),]), offset:80});}
            }).catch((error) => {
              console.log(error);
            })
            this.tableData.list[this.updateIndex] = this.form//数据库修改成功后更新页面表格中的数据
            this.ab = false//关闭修改信息弹窗
          },
          delUser(index, id, username) {
            const h = this.$createElement;
            this.$msgbox({
              title: '消息',
              message: h('p', null, [h('span', null, '是否删除 '), h('i', { style: 'color: teal' }, username)]),
              showCancelButton: true,//显示关闭按钮
              confirmButtonText: '删除',
              cancelButtonText: '取消',
              beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                  instance.confirmButtonLoading = true;
                  instance.confirmButtonText = '执行中...';
                  axios({
                    method : "GET",
                    url:"/user/del/" + id,
                  }).then((response)=>{
                    if (response.data === true){
                        this.$message({type: 'success', center: true, message: '删除成功'});
                        instance.confirmButtonLoading = false;//取消按钮加载状态
                        done();
                        this.tableData.list.splice(index, 1)
                    }
                  }).catch((error) => {
                      done();
                      this.$message({type: 'info', center: true, message: '删除失败'});
                  })
                } else {
                  done();
                }
              }
            }).then(action => {}
            );
          }
        },
        computed:{
          computed_form(){
            return JSON.stringify(this.form)
          },
          computed_selectRole(){
            return JSON.stringify(this.selectRole)
          }
        },
        watch : {
          computed_form:{//深度监听，可监听到对象、数组的变化
            handler(newVal, oldVal){
              let newObj = JSON.parse(newVal);
              let oldObj = JSON.parse(oldVal);
              console.log( newObj.email );
              console.log( oldObj.email );

              if(oldObj.email !== undefined){
                this.formFlag = true
              }
              console.log(this.formFlag)
            },
            immediate: false,
            deep: true,
          },
          computed_selectRole:{//深度监听，可监听到对象、数组的变化
            handler(newVal, oldVal){
              let newObj = JSON.parse(newVal);
              let oldObj = JSON.parse(oldVal);
              console.log( newObj );
              console.log( oldObj.length );
              if(oldObj.length !== 0){
                this.formFlag = true
              }
              console.log(this.formFlag)
            },
            immediate: false,
            deep: true,
          },
/*          form:{//深度监听，可监听到对象、数组的变化
              handler(newVal, oldVal){
                console.log( newVal.email );
                console.log( oldVal.email );
                console.log( newVal === oldVal );

                if(oldVal.email !== undefined){
                  this.formFlag = true
                }
                console.log(this.formFlag)
              },
            immediate: false,
            deep: true,
          },*/
/*          'form.email':{//深度监听，可监听到对象、数组的变化
            handler(newVal, oldVal){
              console.log("form.email: " + "new- " + newVal + "  old- " + oldVal);
            },
            immediate: false,
          }*/
        },
        beforeMount (){//初始化数据
            this.initData(1)
        },
        mounted(){
        },
    }
</script>